﻿#define DEBUG_AGENT

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using SLRTHackathon.DataModels;

namespace SLRTHackathon.Views
{
    public partial class SettingsPage : PhoneApplicationPage
    {
        PeriodicTask resourceIntensiveTask;
        string resourceIntensiveTaskName = "ResourceIntensiveAgent";
        public bool agentIsEnabled = true;
        bool ignoreCheckBoxEvents = false;

        public SettingsPage()
        {
            InitializeComponent();
        }

        private void ResourceIntensiveCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            StartResourceIntensiveAgent();
        }
        private void ResourceIntensiveCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            RemoveAgent(resourceIntensiveTaskName);
        }

        private void StartResourceIntensiveAgent()
        {
            // Variable for tracking enabled status of background agents for this app.
            agentIsEnabled = true;

            resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule.
            if (resourceIntensiveTask != null)
            {
                RemoveAgent(resourceIntensiveTaskName);
            }

            resourceIntensiveTask = new PeriodicTask(resourceIntensiveTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services SettingsPage page on the device.
            int count = CheckData();
            resourceIntensiveTask.Description = "";
            if (count > 0)
            {
                resourceIntensiveTask.Description = "The application has " + count + "expired dependencies.";
            }

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(resourceIntensiveTask);
                ResourceIntensiveStackPanel.DataContext = resourceIntensiveTask;

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(resourceIntensiveTaskName, TimeSpan.FromSeconds(20));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                    agentIsEnabled = false;
                    ResourceIntensiveCheckBox.IsChecked = false;
                }
            }
        }

        private int CheckData()
        {
            int counter = 0;
            foreach (CustomDependency customDependency in App.ViewModel.AllCustomDependencies)
            {
                if (customDependency.EndDate.AddDays(-customDependency.NumberOfDaysBeforeEndDate) <= DateTime.Now)
                {
                    counter++;
                }
            }
            foreach (ExtendedInsurance extendedInsurance in App.ViewModel.AllExtendedInsurances)
            {
                if (extendedInsurance.EndDate.AddDays(-extendedInsurance.NumberOfDaysBeforeEndDate) <= DateTime.Now)
                {
                    counter++;
                }
            }
            foreach (Car car in App.ViewModel.AllCars)
            {
                if (car.LocalVignetteEndDate.AddDays(-car.NumberOfDaysBeforeEndDate) <= DateTime.Now)
                {
                    counter++;
                }
            }
            foreach (InternationalVignette internationalVignette in App.ViewModel.AllInternationalVignettes)
            {
                if (internationalVignette.EndDate.AddDays(-internationalVignette.NumberOfDaysBeforeEndDate) <= DateTime.Now)
                {
                    counter++;
                }
            }

            return counter;
        }

        private void RemoveAgent(string name)
        {
            try
            {
                ScheduledActionService.Remove(name);
            }
            catch (Exception)
            {
                MessageBox.Show("This should never happen!");
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            ignoreCheckBoxEvents = true;

            resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as PeriodicTask;
            if (resourceIntensiveTask != null)
            {
                ResourceIntensiveStackPanel.DataContext = resourceIntensiveTask;
            }

            ignoreCheckBoxEvents = false;
        }
    }
}